package com.trigsoft.applist;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.RelativeLayout.LayoutParams;

import com.devsmart.android.ui.HorizontalListView;
import com.guohead.sdk.GuoheAdLayout;
import com.guohead.sdk.GuoheAdManager;
import com.trigsoft.utils.BitmapUtil;
import com.trigsoft.utils.CatGetter;
import com.trigsoft.utils.FileUtils;
import com.trigsoft.utils.NetworkUtils;
import com.trigsoft.utils.PrefUtil;
import com.trigsoft.utils.ProgressDialogUtils;

public class AppListAct extends Activity implements OnItemClickListener, OnItemLongClickListener
{
	ArrayList<String> catsChinese;

	private class ExportTask extends AsyncTask<Void, Integer, Boolean>
	{
		/*@Override
		protected void onPreExecute()
		{
			mProgressDialog = ProgressDialogUtils.show(mProgressDialog, AppListAct.this, R.string.export_dialog_title, R.string.export_dialog_message);
		}*/

		@Override
		protected Boolean doInBackground(Void... arg0)
		{

			// TODO Auto-generated method stub
			Cursor cursor = DBHelper.queryForExport();
			//int appNum = cursor.getCount();
			//mProgressDialog.setMax(appNum);

			StringBuilder s = new StringBuilder();
			while (cursor.moveToNext())
			{
				s.append(cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LABEL)));
				s.append("(");
				s.append(cursor.getString(cursor.getColumnIndex(DBHelper.KEY_PKG)));
				s.append(")");
				s.append("\n");
				//publishProgress(cursor.getPosition());
			}
			FileUtils.write("sdcard/applist", s.toString());
			return null;
		}

		/*@Override
		protected void onProgressUpdate(Integer... values)
		{
			mProgressDialog.setProgress(values[0].intValue());
			super.onProgressUpdate(values);
		}*/

		@Override
		protected void onPostExecute(Boolean arg0)
		{
			//ProgressDialogUtils.dismiss(mProgressDialog);
			Toast.makeText(AppListAct.this, AppListAct.this.getString(R.string.exportMessage), Toast.LENGTH_SHORT)
					.show();
		}

	}

	private class InitTask extends AsyncTask<Void, Integer, Boolean>
	{
		@Override
		protected Boolean doInBackground(Void... arg0)
		{
			// TODO Auto-generated method stub
			PackageManager pkgMgt = getPackageManager();

			//to query all launcher & load into List<>   
			Intent it = new Intent(Intent.ACTION_MAIN);
			it.addCategory(Intent.CATEGORY_LAUNCHER);

			final List<ResolveInfo> ra = pkgMgt.queryIntentActivities(it, 0);

			int appNum = ra.size();
			mProgressDialog.setMax(appNum);
			//Save the application into database

			for (ResolveInfo info : ra)
			{
				//Bitmap b = ((BitmapDrawable) (info.loadIcon(pkgMgt))).getBitmap();
				Bitmap b = BitmapUtil.createIconBitmap(info.loadIcon(pkgMgt), AppListAct.this);
				String n = info.activityInfo.name;
				String pkg = info.activityInfo.packageName;
				String l = info.loadLabel(pkgMgt).toString();
				String pinyin = PinyinTransformer.getPingYinInitial(l);
				String dn;
				try
				{
					dn = pkgMgt.getApplicationInfo(pkg, 0).loadLabel(pkgMgt).toString();
				} catch (NameNotFoundException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					dn = "";
				}
				int d = dn.compareTo(l) == 0 ? App.YES : App.NO;
				IconCache.icons.remove(l);
				IconCache.icons.put(l, b);
				DBHelper.createOrUpdate(new App(b, n, pkg, pinyin, l, d));
				publishProgress(ra.indexOf(info) + 1);
			}

			return null;
		}

		@Override
		protected void onPostExecute(Boolean arg0)
		{
			mProgressDialog.dismiss();
			if (showCat)
				new CatTask(false).execute();
			else
				setView();
		}

		@Override
		protected void onPreExecute()
		{
			mProgressDialog = ProgressDialogUtils.show(mProgressDialog, AppListAct.this,
					R.string.initialization_dialog_title, R.string.initialization_dialog_message);

		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{
			mProgressDialog.setProgress(values[0].intValue());
			super.onProgressUpdate(values);
		}

	}

	private class RefreshTask extends InitTask
	{
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			mProgressDialog.setTitle(R.string.refresh_dialog_title);
			mProgressDialog.setMessage(AppListAct.this.getResources().getString(R.string.refresh_dialog_message));
		}
	}

	public enum TaskType
	{
		INIT, UPGRADE
	}

	private class UpgradeTask extends AsyncTask<Void, Integer, Boolean>
	{
		@Override
		protected Boolean doInBackground(Void... arg0)
		{

			// TODO Auto-generated method stub
			if (DBHelper.OLD_VERSION < 6)
			{
				PackageManager pkgMgt = getPackageManager();

				//to query all launcher & load into List<>   
				Intent it = new Intent(Intent.ACTION_MAIN);
				it.addCategory(Intent.CATEGORY_LAUNCHER);

				final List<ResolveInfo> ra = pkgMgt.queryIntentActivities(it, 0);

				int appNum = ra.size();

				mProgressDialog.setMax(appNum);

				DBHelper.upgrade(AppListAct.this);
				//Save the application into database

				for (ResolveInfo info : ra)
				{
					//Bitmap b = ((BitmapDrawable) (info.loadIcon(pkgMgt))).getBitmap();
					Bitmap b = BitmapUtil.createIconBitmap(info.loadIcon(pkgMgt), AppListAct.this);
					String n = info.activityInfo.name;
					String pkg = info.activityInfo.packageName;
					String l = info.loadLabel(pkgMgt).toString();
					String pinyin = PinyinTransformer.getPingYinInitial(l);
					String dn;
					try
					{
						dn = pkgMgt.getApplicationInfo(pkg, 0).loadLabel(pkgMgt).toString();
					} catch (NameNotFoundException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
						dn = "";
					}
					int d = dn.compareTo(l) == 0 ? App.YES : App.NO;
					IconCache.icons.remove(l);
					IconCache.icons.put(l, b);
					DBHelper.createOrUpdate(new App(b, n, pkg, pinyin, l, d));
					publishProgress(ra.indexOf(info) + 1);
				}
			}

			if (DBHelper.OLD_VERSION == 6)
				DBHelper.upgrade(AppListAct.this);
			return null;
		}

		@Override
		protected void onPostExecute(Boolean arg0)
		{
			mProgressDialog.dismiss();
			if (showCat)
				new CatTask(false).execute();
			else
				setView();
		}

		@Override
		protected void onPreExecute()
		{
			mProgressDialog = ProgressDialogUtils.show(mProgressDialog, AppListAct.this, R.string.upgrade_dialog_title,
					R.string.upgrade_dialog_message);
		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{
			mProgressDialog.setProgress(values[0].intValue());
			super.onProgressUpdate(values);
		}

	}

	private ProgressDialog mProgressDialog;
	private String[] alphabet;

	private boolean alphabetOnLeft;

	private boolean recentTask;;

	private boolean showCat;

	private GridByAlphaAdapter aAdapter;

	private ArrayList<String> cats;

	private boolean wifi;

	int alphaPos = 0;
	int catPos = 0;
	boolean viewLoaded = false;

	static
	{
		//AdManager.init("d21b9925f3738550 ", "25133bf65b73e550 ", 30, false, "1.4");
	}

	private void getPreference()
	{
		alphabetOnLeft = PrefUtil.checkAlphabetOnLeft(this);
		recentTask = PrefUtil.checkRecentTask(this);
		showCat = PrefUtil.checkShowCat(this);
	}

	protected void load()
	{

		if (DBHelper.toUpgrade)
			new UpgradeTask().execute();
		else
		{
			if (showCat)
				getCats();
			setView();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
		{
			setLandScapeView();
		} else
		{
			setPortraitView();
		}
		loadData(false);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		Thread.setDefaultUncaughtExceptionHandler(new PostMortemReportExceptionHandler(this));
		requestWindowFeature(Window.FEATURE_NO_TITLE); //Remove the activity title

		GuoheAdManager.init("390f0b19c859ce63a88d96662dc15544");
		//viewLoaded = false;
		super.onCreate(savedInstanceState);

		//Fix the bug that addCat is in Chinese in pref
		PrefUtil.upgradePref(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// populate menu items
		new MenuInflater(getApplication()).inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		DBHelper.close();
		GuoheAdManager.finish(this);
		super.onDestroy();
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		// TODO Auto-generated method stub
		if (arg0.getId() == R.id.alpha)
		{ //Click the alpha in the alpha list
			alphaPos = arg2;

			ExpandableListView listView = (ExpandableListView) findViewById(R.id.listByAlpha);

			listView.setSelectedGroup(aAdapter.getPosition(arg2));
		} else if (arg0.getId() == R.id.cat)
		{
			catPos = arg2;
			if (arg2 == 0)
				showGridByAlpha(BitmapUtil.isPortrait(this), false);
			else
				showCatGrid(cats.get(arg2));
		} else
		{
			String n = "";
			String p = "";
			if (arg0.getAdapter().getClass() == TaskAdapter.class)
			{
				Object obj = arg0.getItemAtPosition(arg2);
				if (obj.getClass() == ActivityManager.RecentTaskInfo.class)
				{
					ActivityManager.RecentTaskInfo task = (RecentTaskInfo) obj;
					Intent intent = new Intent(task.baseIntent);
					if (task.origActivity != null)
					{
						intent.setComponent(task.origActivity);
					}
					intent.setFlags((intent.getFlags() & ~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
					try
					{
						startActivity(intent);
					} catch (Exception e)
					{

						p = intent.getComponent().getPackageName();
						Cursor c = DBHelper.queryByPKG(p);
						if (c.moveToFirst())
							n = c.getString(c.getColumnIndex(DBHelper.KEY_NAME));
						else
							n = "";
						c.close();

						startActivity(App.setActivity(p, n));
					}
				} else
				{
					App app = (App) obj;
					n = app.getName();
					p = app.getPkgName();
					try
					{
						startActivity(App.setActivity(p, n));
					} catch (ActivityNotFoundException e)
					{
						DBHelper.deleteAppEntry(p);
					}
				}
			} else
			{
				Cursor c = (Cursor) arg0.getItemAtPosition(arg2);
				n = c.getString(c.getColumnIndex(DBHelper.KEY_NAME));
				if (n == null)
				{
					Toast.makeText(this, "此程序没有应用界面,无法启动，请查看是用说明。", Toast.LENGTH_SHORT).show();
					return;
				}
				p = c.getString(c.getColumnIndex(DBHelper.KEY_PKG));
				try
				{
					startActivity(App.setActivity(p, n));
				} catch (ActivityNotFoundException e)
				{
					DBHelper.deleteAppEntry(p);
				}
			}

			finish();
		}
	}

	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		// TODO Auto-generated method stub
		/*String pkg;
		String name;
		String shortcutName;

		Bitmap bitmap;

		if (arg0.getAdapter().getClass() == TaskAdapter.class)
		{
			ResolveInfo ri = (ResolveInfo) arg0.getItemAtPosition(arg2);
			pkg = ri.activityInfo.packageName;
			name = ri.activityInfo.name;

			PackageManager pm = getPackageManager();
			shortcutName = ri.loadLabel(pm).toString();

			bitmap = ((BitmapDrawable) ri.loadIcon(pm)).getBitmap();
		} else
		{
			Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2);

			pkg = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_PKG));
			name = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_NAME));
			shortcutName = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LABEL));

			byte[] b = cursor.getBlob(cursor.getColumnIndex(DBHelper.KEY_ICON));

			bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);

		}
		final DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		final int iconSize = (int) (getResources().getDimension(android.R.dimen.app_icon_size) * dm.density);

		Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
		shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		shortcutIntent.setComponent(new ComponentName(pkg, name));
		shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
		Bitmap icon = Bitmap.createScaledBitmap(bitmap, iconSize, iconSize, true);
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
		sendBroadcast(intent);*/
		new ContextDialog(this, arg0, arg2).show();
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.preferenceMenu:
			startActivity(new Intent(this, PreferenceActivity.class));
			//startActivityForResult(new Intent(this, PreferenceAct.class), 0);
			break;
		case R.id.exceptionMenu:
			startActivity(new Intent(this, ExceptionListAct.class));
			break;
		case R.id.statistMenu:
			startActivity(new Intent(this, StatisticsAct.class));
			break;
		case R.id.refreshMenu:
			new RefreshTask().execute();
			break;
		case R.id.exportMenu:
			new ExportTask().execute();
			break;
		case R.id.catMenu:
			new CatTask(true).execute();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		getPreference();

		wifi = NetworkUtils.isWiFiActive(this);
		if (recentTask)
			alphabet = getResources().getStringArray(R.array.alphabetWithRecentTask);

		else
			alphabet = getResources().getStringArray(R.array.alphabet);

		DBHelper.init(this);
		if (DBHelper.isEmpty())
			new InitTask().execute();
		else
		{
			//updData();
			//DBHelper.addMyself(this);
			if (!DBHelper.toUpgrade)
				AppStatist.getStatistics(this);
			load();
		}
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);
	}

	private class CatTask extends AsyncTask<Void, Integer, Boolean>
	{
		ArrayList<String> pkgs;
		CatGetter cg;
		private boolean searchWeb;
		private boolean notCat = false;

		public CatTask(boolean searchWeb)
		{
			this.searchWeb = searchWeb;
		}

		@Override
		protected Boolean doInBackground(Void... arg0)
		{
			// TODO Auto-generated method stub

			if (pkgs != null)
			{
				int num = 1;
				for (String pkg : pkgs)
				{
					String cat = cg.getCat(pkg, searchWeb);
					if (cat.contains("other"))
						notCat = true;
					DBHelper.updateCat(cat, pkg);
					publishProgress(num);
					num++;
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean arg0)
		{
			DBHelper.detachCat();
			mProgressDialog.dismiss();
			if (showCat)
			{
				getCats();
				loadCats(BitmapUtil.isPortrait(AppListAct.this));
			}
			setView();
			if (notCat && !searchWeb)
				Toast.makeText(AppListAct.this, getString(R.string.cat_later), Toast.LENGTH_LONG).show();
		}

		@Override
		protected void onPreExecute()
		{
			DBHelper.attachCat(AppListAct.this);
			mProgressDialog = ProgressDialogUtils.show(mProgressDialog, AppListAct.this, R.string.cat_dialog_title,
					R.string.cat_dialog_message);
			pkgs = DBHelper.getPkgNotCat();
			cg = new CatGetter(AppListAct.this);
			mProgressDialog.setMax(pkgs.size());
		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{
			mProgressDialog.setProgress(values[0].intValue());
			super.onProgressUpdate(values);
		}

	}

	private void setLandScapeView()
	{
		setContentView(R.layout.landscape);

		HorizontalListView alphaListview = (HorizontalListView) findViewById(R.id.alpha);
		alphaListview.setVisibility(View.VISIBLE);
		alphaListview.setAdapter(new ArrayAdapter<String>(this, R.layout.alpha_bottom, alphabet));
		alphaListview.setOnItemClickListener(this);

		if (showCat)
		{
			//catsChinese = new CatsFactory().getCats(this);
			loadCats(false);
		} else
			findViewById(R.id.cat).setVisibility(View.GONE);

		//this.showGridByAlpha(false, loadData);

		if (wifi)
		{
			RelativeLayout.LayoutParams GuoheAdLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			GuoheAdLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
			RelativeLayout footer = (RelativeLayout) findViewById(R.id.adLayout);
			GuoheAdLayout adLayout = new GuoheAdLayout(this);
			footer.addView(adLayout, GuoheAdLayoutParams);
		}
	}

	public void loadCats(boolean isPortrait)
	{
		if (isPortrait)
		{
			HorizontalListView catListview = (HorizontalListView) findViewById(R.id.cat);
			if (catListview != null)
			{
				catListview.setVisibility(View.VISIBLE);
				catListview.setAdapter(new ArrayAdapter<String>(this, R.layout.cat_item_bottom, catsChinese));
				catListview.setOnItemClickListener(this);
			}
		} else
		{
			ListView lv = (ListView) findViewById(R.id.cat);
			if (lv != null)
			{
				lv.setVisibility(View.VISIBLE);
				lv.setAdapter(new ArrayAdapter<String>(this, R.layout.cat_item_side, catsChinese));
				lv.setOnItemClickListener(this);
			}
		}
	}

	private void setView()
	{
		if (!viewLoaded)
		{
			if (BitmapUtil.isPortrait(this))
				setPortraitView();
			else
				setLandScapeView();
			viewLoaded = true;
		}
		loadData(true);
	}

	private void setPortraitView()
	{
		//Log.d("TEST", singlePage.toString()+firstPage+alphaPosition);

		//Log.d("TEST", "falsealphaPage");
		//if (alphaPosition.compareTo(AppListPref.LEFT) == 0)
		//Debug.startMethodTracing("calc");

		if (alphabetOnLeft)
		{
			setContentView(R.layout.mainleft);
			/*if (NetworkUtils.isWiFiActive(this))
			{
				AdView adView = new AdView(this);
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(0, LayoutParams.FILL_PARENT);
				params.addRule(RelativeLayout.RIGHT_OF, R.id.listByAlpha);
				addContentView(adView, params);
			}*/

			//Log.d("TEST", "left");
		} else
		{
			setContentView(R.layout.mainright);
			//Log.d("TEST", "right");
		}

		ListView lv = (ListView) findViewById(R.id.alpha);
		if (wifi)
			lv.setAdapter(new ArrayAdapter<String>(this, R.layout.alpha_wifi, alphabet));
		else
			lv.setAdapter(new ArrayAdapter<String>(this, R.layout.alpha_no_wifi, alphabet));
		//lv.setAdapter(new AlphaAdapter(this, alphaList));
		lv.setVisibility(View.VISIBLE);
		lv.setOnItemClickListener(this);

		if (showCat)
		{
			//catsChinese = new CatsFactory().getCats(this);
			loadCats(true);
		} else
			findViewById(R.id.cat).setVisibility(View.GONE);
		//this.showGridByAlpha(true, loadData);
		//Debug.stopMethodTracing();

		if (wifi)
		{
			RelativeLayout.LayoutParams GuoheAdLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			GuoheAdLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
			RelativeLayout footer = (RelativeLayout) findViewById(R.id.adLayout);
			GuoheAdLayout adLayout = new GuoheAdLayout(this);
			footer.addView(adLayout, GuoheAdLayoutParams);
		}
	}

	public void loadData(boolean loadData)
	{
		if (catPos == 0)
			showGridByAlpha(BitmapUtil.isPortrait(this), loadData);
		else
			showCatGrid(cats.get(catPos));
	}

	private void showCatGrid(String cat)
	{
		Cursor cursor = DBHelper.queryByCat(cat);
		if (cursor.moveToFirst())
		{
			GridView gridView = (GridView) findViewById(R.id.catView);
			final String[] columns = new String[] {DBHelper.KEY_ICON, DBHelper.KEY_LABEL};
			final int[] to = new int[] {R.id.icon, R.id.name};
			SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.item, cursor, columns, to);
			sca.setViewBinder(new ApplicationViewBinder());
			gridView.setAdapter(sca);
			gridView.setVisibility(View.VISIBLE);
			gridView.setOnItemClickListener(this);
			gridView.setOnItemLongClickListener(this);
			findViewById(R.id.allView).setVisibility(View.GONE);
		}
	}

	private void showGridByAlpha(boolean isPortrait, boolean loadData)
	{
		ExpandableListView listView = (ExpandableListView) findViewById(R.id.listByAlpha);
		if (loadData)
		{
			aAdapter = new GridByAlphaAdapter(this, recentTask, isPortrait);
		} else
			aAdapter.setOrientation(isPortrait);

		listView.setOnGroupClickListener(new OnGroupClickListener() {
			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id)
			{
				// TODO Auto-generated method stub
				return true;
			}
		});
		listView.setAdapter(aAdapter);

		findViewById(R.id.catView).setVisibility(View.GONE);
		findViewById(R.id.allView).setVisibility(View.VISIBLE);
		for (int i = 0; i < alphabet.length; i++)
			listView.expandGroup(i);

		listView.setSelectedGroup(aAdapter.getPosition(alphaPos));
	}

	public void getCats()
	{
		LinkedHashSet<String> catInDB = DBHelper.getCats();
		cats = new ArrayList<String>(catInDB.size());
		String[] allCats = {"all", "game", "communication", "photo", "entertainments", "transportation", "lifestyle",
				"shopping", "book", "finance", "tool", "education", "sport", "business", "personalization", "other"};
		String[] allCatsChinese = getResources().getStringArray(R.array.cat);
		catsChinese = new ArrayList<String>(cats.size());
		cats.add(allCats[0]);
		catsChinese.add(allCatsChinese[0]);
		for (int i = 1; i < allCats.length; i++)
		{
			if (catInDB.contains(allCats[i]))
			{
				cats.add(allCats[i]);
				catsChinese.add(allCatsChinese[i]);
			}
		}

		HashSet<String> extraCats = PrefUtil.getAddCat(this);
		for (String c : extraCats)
		{
			if (catInDB.contains(c))
			{
				cats.add(c);
				catsChinese.add(c);
			}
		}

	}
}
